package edu.spec.wechat.controller;

import edu.spec.wechat.kit.SecurityKit;
import edu.spec.wechat.web.WechatContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * Created by MadFrog on 2016/10/13.
 */

@Controller
public class WechatController {

    /**
     * 配置公众平台测试帐号，接口配置信息
     * 微信访问本地的服务器，对服务器有效性进行验证，方式为get，通过约定TOKEN和sha1算法验证，验证通过就返回echostr
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "/wechat", method = RequestMethod.GET)
    public void handleGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        String[] arrs = {WechatContext.getInstance().getBasetoken(), nonce, timestamp};
        Arrays.sort(arrs);
        StringBuffer sb = new StringBuffer();
        for (String a : arrs){
            sb.append(a);
        }
        String sha1 = SecurityKit.sha1(sb.toString());
        if(sha1.equals(signature)){
            resp.getWriter().println(echostr);
        }
    }

    /**
     *  微信访问本地服务器，方式为post
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "/wechat", method = RequestMethod.POST)
    public void handlePost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
//        String replay = MessageKit.handleReceiveMessage(req);
//        resp.setContentType("application/xml;charset=UTF-8");
//        resp.setCharacterEncoding("UTF-8");
//        if (!BasicKit.isEmpty(replay)){
//            resp.getWriter().write(replay);
//        }
        return;
    }

    @RequestMapping("/at")
    public void testAccessToken(HttpServletResponse response){
        try {
            String at = WechatContext.getAccessToken();
            response.getWriter().println(at);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
